package com.hardroid.workload.ui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.hardroid.workload.R;
import com.hardroid.workload.ui.fragment.OpenProjectFragment;
import com.hardroid.workload.utils.Singleton;

public class ProjectHomeActivity extends Activity {

	public final static int EXIT_DIALOG = 3;

	public int m1, h1, m2, h2;

	
	private Button newProjectButton;
	private Button openProjecButton;
	
	AlertDialog exitDialog ;

	private OpenProjectFragment openFragment;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_project_home);

		// mendapatkan fragment open, ada isinya jika activity ini dijalankan pada tablet, null jika pada phone
		openFragment =(OpenProjectFragment) getFragmentManager().findFragmentById(R.id.fragment_open_project);
		
		
		newProjectButton = (Button) findViewById(R.id.main_new_project_button);
		openProjecButton = (Button) findViewById(R.id.main_open_project_button);

		newProjectButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// menjalankan activity new project
				startActivity(new Intent(getApplicationContext(),
						NewProjectActivity.class));
//				finish();
			}
		});
		
		openProjecButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (openFragment == null) {
					// jika bukan tablet
									
				} else {
					// jika tablet
					if (openFragment.getListView().getCheckedItemPosition()!=ListView.INVALID_POSITION){
						openFragment.openProject();						
					}else{
						Toast.makeText(getApplicationContext(), "No project selected", Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure want to exit?").setCancelable(true).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// exit 
				finish();
				System.exit(0);
			}
		}).setNegativeButton("No", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		
		exitDialog = builder.create();
		
		if (openFragment!=null){
			openFragment.getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		showDialog(EXIT_DIALOG);		
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		Dialog dialog;
		switch (id) {
		case EXIT_DIALOG:{
			dialog = exitDialog;
			break;
		}
//		case OpenProjectFragment.TIME_PICKER_START_DIALOG: {
//			dialog = new TimePickerDialog(this,mTimeSetListener, 8,
//					0, true);
//			dialog.setTitle("Start Work");			
//			return dialog;
//
//		}
//		case OpenProjectFragment.TIME_PICKER_END_DIALOG: {
//			dialog = new TimePickerDialog(this, mTimeSetListener2, 17,
//					0, true);
//			dialog.setTitle("End Work");			
//			return dialog;
//		}
		default:
			dialog = null;
		}
		return dialog;
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Singleton.currentProject = null;
		Singleton.employerAdapter = null;
		Singleton.todayReference = null;
	}

	
//
//	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
//		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//			h1= hourOfDay;
//			m1=  minute;			
//			showDialog(OpenProjectFragment.TIME_PICKER_END_DIALOG);
//		}
//	};
//
//	private TimePickerDialog.OnTimeSetListener mTimeSetListener2 = new TimePickerDialog.OnTimeSetListener() {
//		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//			h2= hourOfDay;
//			m2=  minute;
//			Singleton.generateNewReference(m1, h1, m2, h2);
//			Intent i = null;
//			if (UIUtils.isHoneycombTablet(getApplicationContext())) {
//				i = new Intent(getApplicationContext(), DashboardMultiPaneActivity.class);
//
//			} else {
//				i = new Intent(getApplicationContext(), DashboardActivity.class);
//			}
//			startActivity(i);
//			Log.i("Open Project", "New date "+ (Singleton.todayReference==null)+"");
//			if (Singleton.todayReference!=null){
//				Log.i("Singleton", HardroidUtils.dateToSDate(Singleton.todayReference.obsvDate)+"");	
//			}
//			Singleton.saveProject(Singleton.currentProject);
//			finish();
//		}
//	};
	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		getMenuInflater().inflate(R.menu.dashboard_menu, menu);
		getActionBar().setDisplayHomeAsUpEnabled(true);				
	
		return super.onCreateOptionsMenu(menu);
	};
	
	private void copyFile(InputStream in, OutputStream out) throws IOException {
	    byte[] buffer = new byte[1024];
	    int read;
	    while((read = in.read(buffer)) != -1){
	      out.write(buffer, 0, read);
	    }
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.menu_dashboard_tentang_work_sampling:{
//			Intent i = new Intent(getBaseContext(),HelpActivity.class);
//			startActivity(i);
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				File file = new File(Environment.getExternalStorageDirectory()
						+ "/hardroid/worksampling.pdf");
				if (!file.exists()) {
					InputStream stream;
					try {
						stream = getAssets().open("worksampling.pdf");
						if (stream != null) {

							try {
								OutputStream out = null;
								File fileDir = new File(
										Environment
												.getExternalStorageDirectory(),
										"hardroid");
								fileDir.mkdirs();
								File helpFile = new File(fileDir + "/worksampling.pdf");
								if (helpFile.createNewFile()) {
									out = new FileOutputStream(
											Environment
													.getExternalStorageDirectory()
													+ "/hardroid/worksampling.pdf");
									copyFile(stream, out);
									stream.close();
									stream = null;
									out.flush();
									out.close();

									try {
										Uri path = Uri.fromFile(helpFile);
										Intent intent = new Intent(
												Intent.ACTION_VIEW);
										intent.setDataAndType(path,
												"application/pdf");
										intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
										startActivity(intent);

									} catch (Exception e) {
										Toast.makeText(
												getBaseContext(),
												"Tidak ada PDF reader yang ditemukan",
												Toast.LENGTH_SHORT).show();
									}
								} else {
									Toast.makeText(getBaseContext(),
											"Gagal mengcopy file help",
											Toast.LENGTH_SHORT).show();
								}
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

				} else {
					try {
						Uri path = Uri.fromFile(new File(Environment
								.getExternalStorageDirectory()
								+ "/hardroid/worksampling.pdf"));
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setDataAndType(path, "application/pdf");
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);

					} catch (Exception e) {
						Toast.makeText(getBaseContext(),
								"Tidak ada PDF reader yang ditemukan",
								Toast.LENGTH_SHORT).show();
					}
				}

			} else {
				Toast.makeText(getBaseContext(),
						"Tidak ada SD card yang ditemukan", Toast.LENGTH_SHORT)
						.show();
			}

			break;
		}
		
		case R.id.menu_dashboard_help:{
//				Intent i = new Intent(getBaseContext(),HelpActivity.class);
//				startActivity(i);

			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				File file = new File(Environment.getExternalStorageDirectory()+"/hardroid/help.pdf");
				if (!file.exists()){
					InputStream stream;
					try {
						stream = getAssets().open("help.pdf");
						if (stream!=null){
							
							try {
								OutputStream out = null;
								File fileDir= new File(Environment.getExternalStorageDirectory(), "hardroid");
								fileDir.mkdirs();
								File helpFile = new File(fileDir+"/help.pdf");
								if (helpFile.createNewFile()){								
									  out = new FileOutputStream(Environment.getExternalStorageDirectory()+"/hardroid/help.pdf");
							          copyFile(stream, out);
							          stream.close();
							          stream = null;
							          out.flush();
							          out.close();
							          
							          try{
										Uri path  = Uri.fromFile(helpFile);														
										Intent intent = new Intent(Intent.ACTION_VIEW);
						                intent.setDataAndType(path, "application/pdf");
						                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						                startActivity(intent);
						                
							          }catch(Exception e){
							        	  Toast.makeText(getBaseContext(), "Tidak ada PDF reader yang ditemukan", Toast.LENGTH_SHORT).show();
							          }
								}else{
									  Toast.makeText(getBaseContext(), "Gagal mengcopy file help", Toast.LENGTH_SHORT).show();
								}
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
								
			}else{
				try{
					Uri path  = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/hardroid/help.pdf"));														
					Intent intent = new Intent(Intent.ACTION_VIEW);
	                intent.setDataAndType(path, "application/pdf");
	                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	                startActivity(intent);
	                
		          }catch(Exception e){
		        	  Toast.makeText(getBaseContext(), "Tidak ada PDF reader yang ditemukan", Toast.LENGTH_SHORT).show();	  
		          }
			}
					
			} else {				
				Toast.makeText(getBaseContext(), "Tidak ada SD card yang ditemukan", Toast.LENGTH_SHORT).show();
			}
							
			
			break;
		}
		case R.id.menu_dashboard_about:{
			Intent i = new Intent(getBaseContext(),AboutActivity.class);
			startActivity(i);
			break;
		}
		}
		return super.onOptionsItemSelected(item);
	}
	
}